package org.jvnet.hudson.client_demo;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Map;

import org.apache.commons.codec.binary.Base64;

public class URLConnectionUtil {
	
	private static final String SERVLET_PUT = "PUT" ;
	
	private static String prepareParam(Map<String,Object> paramMap){
		StringBuffer sb = new StringBuffer();
		if(paramMap.isEmpty()){
			return "" ;
		}else{
			for(String key: paramMap.keySet()){
				String value = (String)paramMap.get(key);
				if(sb.length()<1){
					sb.append(key).append("=").append(value);
				}else{
					sb.append("&").append(key).append("=").append(value);
				}
			}
			return sb.toString();
		}
	}
	
	public static InputStream doGet(String urlStr,boolean isAuth,String usr,String pwd,Map<String,Object> paramMap ) throws Exception{
		String paramStr = prepareParam(paramMap);
		if(paramStr == null || paramStr.trim().length()<1){
			
		}else{
			urlStr +="?"+paramStr;
		}
		URL url = new URL(urlStr);
		HttpURLConnection conn = (HttpURLConnection)url.openConnection();
		
		if (isAuth) {
			String userCredentials = usr+":"+pwd;
			String basicAuth = "Basic " + new String(new Base64().encode(userCredentials.getBytes()));
			conn.setRequestProperty ("Authorization", basicAuth);	
		}
		
		conn.setRequestMethod("GET");
		conn.setRequestProperty("Content-Type","text/html; charset=UTF-8");
		conn.connect();
		
		return conn.getInputStream();
	}
	
	public static void doPut(String urlStr,Map<String,Object> paramMap) throws Exception{
		URL url = new URL(urlStr);
		HttpURLConnection conn = (HttpURLConnection)url.openConnection();
		conn.setRequestMethod(SERVLET_PUT);
		String paramStr = prepareParam(paramMap);
		conn.setDoInput(true);
		conn.setDoOutput(true);
		OutputStream os = conn.getOutputStream();     
		os.write(paramStr.toString().getBytes("utf-8"));     
		os.close();   		
		
		BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
		String line ;
		String result ="";
		while( (line =br.readLine()) != null ){
			result += line;
		}
		System.out.println(result);
		br.close();
				
	}
}
